package org.funtester.performance.books.chapter03.common;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTool {

    /**
     * 创建线程池,固定线程池大小
     * @param size 线程池大小
     * @return
     */
    public static ThreadPoolExecutor createPool(int size) {
        return createPool(size, 10);
    }

    /**
     * 创建线程池,固定线程池大小
     * @param size 线程池大小
     * @param capacity 队列容量
     * @return
     */
    public static ThreadPoolExecutor createPool(int size, int capacity) {
        return new ThreadPoolExecutor(size, size, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(capacity),// 创建线程池
                new ThreadFactory() {// 创建一个线程工厂

                    AtomicInteger index = new AtomicInteger();// 线程安全的线程编号

                    @Override
                    public Thread newThread(Runnable r) {// 重写创建线程方法
                        Thread thread = new Thread(r);// 创建线程
                        thread.setName("线程-" + index.incrementAndGet());// 设置线程名称
                        return thread;// 返回创建的线程
                    }
                });// 创建线程池
    }


    /**
     * 线程休眠
     * @param milliseconds 休眠时间,单位毫秒
     */
    public static void sleep(int milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
